#include <atomic>
#include <thread>
#include <vector>
#include <iostream>
using namespace std;

std::atomic<int> atomic_cnt(0);
atomic_uint32_t atomic_u32(0);
int noatomic_cnt = 0;

void increment() {
    for (int i = 0; i < 10000; ++i) {
        atomic_cnt.fetch_add(1, std::memory_order_relaxed); // Atomically increment the counter
        atomic_u32 ++;
        noatomic_cnt ++;
    }
}

int main() {
    vector<std::thread> threads;
    int i;
    for(i=0;i<10;i++){
        std::thread t1(increment);
        threads.push_back(std::move(t1));

        // 高效方法: 就地构造
        // threads.emplace_back(increment);
    }
    for (auto& thread : threads)
        thread.join();

    cout << "Atomic counter: " << atomic_cnt << endl;
    cout << "atomic_u32 counter: " << atomic_u32 << endl;
    cout << "Non-atomic counter: " << noatomic_cnt << endl;

    return 0;
}

/*
Atomic counter: 100000
atomic_u32 counter: 100000
Non-atomic counter: 92471

*/